package com.hn658.message.receive.business.impl;

import com.hn658.base.message.eventbus.event.Event;
import com.hn658.base.message.eventbus.handler.IEventDealManager;
import com.hn658.base.message.managermq.receive.AbstractMessageListener;
import com.hn658.framework.logging.Logger;
import com.hn658.framework.logging.LoggerFactory;
import com.hn658.framework.logging.enums.LogCategory;
import com.hn658.message.receive.business.IEventReceiveManager;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

/**
 * Created by baihai on 2015/11/25.
 */
@Service("eventReceiveManager")
public class MQEventReceiveManager  extends AbstractMessageListener implements IEventReceiveManager{


    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(MQEventReceiveManager.class);


    @Autowired
    private IEventDealManager eventDealManager;

    @Override
    public void handleEvent(Event event) {

        eventDealManager.handleEvent(event);
    }

    @Override
    public void onMessage(Message message) {

        if(null == message){
            logger.error(LogCategory.SYSTEM, "JMS receive null");
        }else{
            if(message instanceof TextMessage) {//处理TextMessage消息
                try {
                    logger.debug("JMS接收消息:{}", ((TextMessage) message).getText());
                    // 转换事件
                    Event event = jsonMapper.fromJson(((TextMessage) message).getText(), Event.class);
                    // 处理事件
                    this.handleEvent(event);
                } catch (JMSException e) {
                    logger.error("EventBus 接受JMS信息时发生异常:{}", ExceptionUtils.getStackTrace(e));
                    // TODO JMS 接收消息异常处理
                }
            }
        }
    }
}
